<?php
/**
* A database class
*
* The database class is used to create a connection to 
* the database and deal with questions to and from the database
*
* @author dmq (master@dmq.se)
*/

class Database
{
	const HOST = "213.180.89.119";
	const USER = "irinoriuser";
	const PASSWORD = "irinoripw";
	const DATABASE = "irinori";

	private $mysqli = null;
	private $transactionStatus = true;


	// Open db connection.
	public function Open()
	{
		$this->mysqli = @new mysqli( self::HOST, self::USER, self::PASSWORD, self::DATABASE );
		if ( $this->mysqli->connect_errno )
		{
			Error::Database( $this->mysqli );
			die();
		}

		return true;
	}

	// Open and return a new connection.
	public function OpenNew()
	{
		$connection = new Database();
		$connection->Open();

		return $connection;
	}

	// Close db connection.
	public function Close()
	{
		$this->mysqli->close();
		$this->mysqli = null;
	}

	// Return prepare statement.
	public function Prepare( $sql )
	{
		return $this->mysqli->prepare( $sql );
	}

	// Direct query.
	public function Query( $sql )
	{
		return $this->mysqli->query( $sql );
	}

	// Escape before db insertment.
	public function Escape( $string )
	{
		return $this->mysqli->real_escape_string( $string );
	}

	// Last insert id.
	public function LastInsertId()
	{
		return $this->mysqli->insert_id;
	}

	public function AffectedRows()
	{
		return $this->mysqli->affected_rows;
	}

	public function StartTransaction()
	{
		$this->mysqli->autocommit( false );
		$this->mysqli->transactionStatus = true;
	}

	public function Execute( $stmt )
	{
		if ( !( $status = $stmt->execute() ) )
		{
			$this->mysqli->transactionStatus = false;
		}

		return $status;
	}

	public function EndTransaction()
	{
		if ( !$this->mysqli->transactionStatus )
		{
			$this->mysqli->rollback();
		}
		else
		{
			$this->mysqli->commit();
		}

		$this->mysqli->autocommit( true );

		return $this->mysqli->transactionStatus;
	}
}
